package org.nowcoder.leetcode.slidingWindow;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Title  : 187. Repeated DNA Sequences
 * Source : https://leetcode.cn/problems/repeated-dna-sequences/
 * Author : XrazYang
 * Date   : 2023-07-25
 */

public class LeetCode_187 {
    public List<String> findRepeatedDnaSequences(String s) {
        // Map<String, Integer> results = new HashMap<>();
        // //处理特殊情况
        // if (s.length() > 10) {
        //     StringBuilder builder = new StringBuilder();
        //     for (int right = 0; right < s.length(); right++) {
        //         char c = s.charAt(right);
        //         if (right < 10) { //初始化
        //             builder.append(c);
        //         } else {
        //             String str = builder.toString();
        //             if (results.containsKey(str)) {
        //                 results.put(str, results.get(str) + 1);
        //             }  else {
        //                 results.put(str, 1);
        //             }
        //             builder.delete(0, 1);
        //             builder.append(c);
        //         }
        //     }
        // //处理最后一个
        //     String str = builder.toString();
        //     if (results.containsKey(str)) {
        //         results.put(str, results.get(str) + 1);
        //     } else {
        //         results.put(str, 1);
        //     }
        // }
        // return results.entrySet().stream().filter(entry -> entry.getValue() > 1).map(Map.Entry::getKey).collect(Collectors.toList());

        Map<String, Integer> results = new HashMap<>();
        //处理特殊情况
        if (s.length() > 10) {
            int left = 0;
            for (int right = 0; right < s.length(); right++) {
                if (right >= 10) {
                    String str = s.substring(left++, right);
                    results.put(str, results.getOrDefault(str, 0) + 1);
                }
            }
            //处理最后一个子序列
            String str = s.substring(left);
            results.put(str, results.getOrDefault(str, 0) + 1);
        }
        return results.entrySet().stream().filter(entry -> entry.getValue() > 1).map(Map.Entry::getKey).collect(Collectors.toList());
    }
}
